[id].ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { defineEventHandler, EventHandlerRequest } from 'h3';
  2. import { DB } from '~~/server/db/DB';
  3. import { createErrorResponse, createSuccessResponse, IResponse } from '~~/server/utils/response';
  4. import { IChannel } from '../channel/[id]';
  5. export interface IArticle {
  6. id: number;
  7. model_id: number;
  8. channel_id: number;
  9. title: string;
  10. desc: string;
  11. image: string,
  12. images: string;
  13. seotitle: string;
  14. keywords: string;
  15. description: string;
  16. tags: string;
  17. diyname: string;
  18. publishtime: number;
  19. createtime: number;
  20. views: number;
  21. content: string;
  22. channel: IChannel;
  23. }
  24. export default defineEventHandler<EventHandlerRequest, Promise<IResponse<IArticle>>>(async (event) => {
  25. try {
  26. const id = event.context.params?.id;
  27. if (!id)
  28. return createErrorResponse('分类ID不能为空');
  29. const article = await DB.table('pr_cms_archives')
  30. .where('id', id)
  31. .where('status', 'normal')
  32. .first();
  33. if (!article)
  34. return createErrorResponse('文章不存在');
  35. const channel = await DB.table('pr_cms_channel')
  36. .where('id', article.channel_id)
  37. .first();
  38. if (!channel)
  39. return createErrorResponse('分类不存在');
  40. article.channel = channel;
  41. // 2. 通过model_id从pr_cms_model表中获取table字段
  42. const model = await DB.table('pr_cms_model')
  43. .where('id', article.model_id)
  44. .select('table')
  45. .first();
  46. if (!model)
  47. return createErrorResponse('分类不存在');
  48. // 3. 通过table指定的表通过id查出content
  49. const content = await DB.table(`pr_${model.table}`)
  50. .where('id', id)
  51. .select('content')
  52. .first();
  53. // 4. 合并返回结果
  54. if (content && content['content']) {
  55. article.content = content['content'];
  56. }
  57. return createSuccessResponse(article);
  58. } catch (error) {
  59. return createErrorResponse(error);
  60. }
  61. });